package eerbaar.shared.persist.internal.lib;

import eerbaar.body.BodyFactory;
import eerbaar.body.IBrain;
import eerbaar.memory.IMemory;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersistService;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.INode;


public class BrainPersister implements IPersister<IBrain> {

    private IBrain target;

    public BrainPersister() {
        //
    }

    public BrainPersister(IBrain wrapper) {
        this.target = wrapper;
    }

    public BrainPersister(INode node) throws GameRuntimeException {
        load(node);
    }

    @Override
    public Class<IBrain> getRegistertedInterface() {

        return IBrain.class;
    }

    @Override
    public MemoryPersister[] getSavableChildren() {

        MemoryPersister p = new MemoryPersister(this.target.getMemory());
        return new MemoryPersister[] { p };
    }

    @Override
    public String getSavableName() {

        return "brain";
    }

    @Override
    public IBrain getTarget() {

        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> persist) {
        return false;
    }

    @Override
    public IBrain load(INode node) {
        assert (node != null);
        assert (node.getChildCount() == 1);

        IPersistService service = ServiceFactory
                .getService(IPersistService.class);
        IPersister<IMemory> p = service.getPersister(IMemory.class);
        IMemory memory = p.load(node.getChild(0));

        return BodyFactory.createBrain(memory);
    }

    @Override
    public void saveAttributes(INode node) {
        //
    }

    @Override
    public void setTarget(IBrain obj) {
        this.target = obj;
    }

}
